﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Serialization;
using JTT.Dev.Wechat.Entity;
using JTT.Dev.Toolkit.XML;
using JTT.Dev.Toolkit.NET;
using JTT.Dev.Toolkit.JSON;
using JTT.Dev.Toolkit.Crypto;

namespace JTT.Dev.Wechat
{

    /// <summary>
    /// 聚途塔微信控制对象
    /// </summary>
    public class JTTWechatHelper
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        public JTTWechatHelper()
        {
        }

        /// <summary>
        /// 得到微信接收信息
        /// </summary>
        /// <param name="_RequestString"></param>
        /// <returns></returns>
        public JTTWechatReceiveMessage GetWechatReceiveMessage(String _RequestString)
        {
            return _RequestString.XmlToObject<JTTWechatReceiveMessage>();
        }

        /// <summary>
        /// 返回微信消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_Object"></param>
        /// <returns></returns>
        public String ReturnWechatMessage<T>(T _Object)
        {
            return _Object.ObjectToXml<T>();
        }

        /// <summary>
        /// 获得公众账号访问密钥
        /// </summary>
        /// <param name="_AppID"></param>
        /// <param name="_AppSecret"></param>
        /// <returns></returns>
        public String GetWechatPubAccessToken(String _AppID, String _AppSecret)
        {
            String AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _AppID + "&secret=" + _AppSecret;
            String TempJSON = NETHelper.URLGet(AccessTokenUrl);
            try
            {
                JTTWechatGetAccessToken MyJTTWechatGetAccessToken = TempJSON.JsonToObject<JTTWechatGetAccessToken>();
                return MyJTTWechatGetAccessToken.AccessToken;
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 获得用户信息
        /// </summary>
        /// <param name="_AccessToken"></param>
        /// <param name="_OpenID"></param>
        /// <returns></returns>
        public JTTWechatUserInfo GetUserInfo(String _AccessToken, String _OpenID)
        {
            String GetURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + _AccessToken + "&openid=" + _OpenID + "&lang=zh_CN";
            String TempJSON = NETHelper.URLGet(GetURL);
            try
            {
                JTTWechatUserInfo MyJTTWechatUserInfo = TempJSON.JsonToObject<JTTWechatUserInfo>();
                return MyJTTWechatUserInfo;
            }
            catch (Exception)
            {
                return new JTTWechatUserInfo();
            }
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        public Boolean SendTemplateMessage(String _AccessToken, JTTWechatTemplateMessage _TemplateMessage)
        {
            try
            {
                String PostBody = _TemplateMessage.ObjectToJson2();
                String PostUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + _AccessToken;
                String ReturnJson = NETHelper.TextMessagePost(PostUrl, PostBody);

                JTTWechatTemplateSendResult TempResult = ReturnJson.JsonToObject<JTTWechatTemplateSendResult>();
                if (TempResult.ErrorCode == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 发送客服文本消息
        /// </summary>
        /// <param name="_AccessToken"></param>
        /// <param name="_Message"></param>
        /// <returns></returns>
        public Boolean SendCustomTextMessage(String _AccessToken, JTTWechatCustomTextMessage _Message)
        {
            try
            {
                //String PostBody = _Message.ObjectToJson<JTTWechatCustomTextMessage>();
                String PostBody = _Message.ObjectToJson2();
                String PostUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + _AccessToken;
                String ReturnJson = NETHelper.TextMessagePost(PostUrl, PostBody);

                JTTWechatCustomMessageReturn TempResult = ReturnJson.JsonToObject<JTTWechatCustomMessageReturn>();
                if (TempResult.ErrorCode == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 发送客服图盘消息
        /// </summary>
        /// <param name="_AccessToken"></param>
        /// <param name="_Message"></param>
        /// <returns></returns>
        public Boolean SendCustomImageMessage(String _AccessToken, JTTWechatCustomImageMessage _Message)
        {
            try
            {
                String PostBody = _Message.ObjectToJson<JTTWechatCustomImageMessage>();
                String PostUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + _AccessToken;
                String ReturnJson = NETHelper.TextMessagePost(PostUrl, PostBody);
                JTTWechatCustomMessageReturn TempResult = ReturnJson.JsonToObject<JTTWechatCustomMessageReturn>();
                if (TempResult.ErrorCode == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取网页授权码
        /// </summary>
        /// <param name="_AppID"></param>
        /// <param name="_AppSecret"></param>
        /// <param name="_Code"></param>
        /// <returns></returns>
        public JTTWechatOAuthAccessToken GetOAuthAccessToken(String _Code, String _AppID, String _AppSecret)
        {
            String GetURL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + _AppID + "&secret=" + _AppSecret + "&code=" + _Code + "&grant_type=authorization_code";
            try
            {
                String TempJSON = NETHelper.URLGet(GetURL);
                JTTWechatOAuthAccessToken MyWechatOAuthAccessToken = TempJSON.JsonToObject<JTTWechatOAuthAccessToken>();
                return MyWechatOAuthAccessToken;
            }
            catch (Exception)
            {
                return new JTTWechatOAuthAccessToken();
            }
        }

        /// <summary>
        /// 获取JSTicket
        /// </summary>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public JTTWechatJSTicket GetJSTicket(String _AccessToken)
        {
            String GetURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + _AccessToken + "&type=jsapi";
            try
            {
                String TempJSON = NETHelper.URLGet(GetURL);
                JTTWechatJSTicket MyJTTWechatJSTicket = TempJSON.JsonToObject<JTTWechatJSTicket>();
                return MyJTTWechatJSTicket;
            }
            catch (Exception)
            {
                return new JTTWechatJSTicket();
            }
        }

        /// <summary>
        /// 获得JS签名
        /// </summary>
        /// <param name="_Noncestr"></param>
        /// <param name="_JSTicket"></param>
        /// <param name="_TimeStamp"></param>
        /// <param name="_URL"></param>
        /// <returns></returns>
        public String GetJSSDKSignature(String _Noncestr, String _JSTicket, Int64 _TimeStamp, String _URL)
        {
            string CombineString = "";
            CombineString = "jsapi_ticket=" + _JSTicket + "&noncestr=" + _Noncestr + "&timestamp=" + _TimeStamp.ToString() + "&url=" + _URL;

            SHA1 MyMySHA1;
            ASCIIEncoding MyEncoding;
            String ReturnHash = "";
            try
            {
                MyMySHA1 = new SHA1CryptoServiceProvider();
                MyEncoding = new ASCIIEncoding();
                byte[] dataToHash = MyEncoding.GetBytes(CombineString);
                byte[] dataHashed = MyMySHA1.ComputeHash(dataToHash);
                ReturnHash = BitConverter.ToString(dataHashed).Replace("-", "");
                ReturnHash = ReturnHash.ToLower();
            }
            catch (Exception)
            {
                ReturnHash = "";
            }
            return ReturnHash;
        }

        #region "带参数的二维码"

        /// <summary>
        /// 获取永久二维码地址
        /// </summary>
        /// <param name="_SceneInfo"></param>
        /// <returns></returns>
        public JTTWechatQRLimitSceneInfo CreateLimitQRScene(String _AccessToken, JTTWechatQRLimitScene _SceneInfo)
        {
            String PostString = _SceneInfo.ObjectToJson<JTTWechatQRLimitScene>();
            String PostURL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + _AccessToken;
            try
            {
                String ReturnJson = NETHelper.TextMessagePost(PostURL, PostString);
                JTTWechatQRLimitSceneReturn TempResult = ReturnJson.JsonToObject<JTTWechatQRLimitSceneReturn>();
                JTTWechatQRLimitSceneInfo TempInfo = new JTTWechatQRLimitSceneInfo();
                TempInfo.ImageText = TempResult.URL;
                TempInfo.ImageURL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + TempResult.Ticket;
                return TempInfo;
            }
            catch (Exception)
            {
                return new JTTWechatQRLimitSceneInfo();
            }
        }

        /// <summary>
        /// 获取临时二维码地址
        /// </summary>
        /// <param name="_SceneInfo"></param>
        /// <returns></returns>
        public JTTWechatQRTempSceneInfo CreateTempQRScene(String _AccessToken, JTTWechatQRTempScene _SceneInfo)
        {
            String PostString = _SceneInfo.ObjectToJson<JTTWechatQRTempScene>();
            String PostURL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + _AccessToken;
            try
            {
                String ReturnJson = NETHelper.TextMessagePost(PostURL, PostString);
                JTTWechatQRTempSceneReturn TempResult = ReturnJson.JsonToObject<JTTWechatQRTempSceneReturn>();
                JTTWechatQRTempSceneInfo TempInfo = new JTTWechatQRTempSceneInfo();
                TempInfo.ImageText = TempResult.URL;
                TempInfo.ImageURL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + TempResult.Ticket;
                return TempInfo;
            }
            catch (Exception)
            {
                return new JTTWechatQRTempSceneInfo();
            }
        }

        #endregion

        #region "微信支付"

        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="_Request"></param>
        /// <returns></returns>
        public JTTWechatWXPayUnifiedOrderReturn UnifiedOrder(JTTWechatWXPayUnifiedOrder _Request, String _WechatPayAPI)
        {
            #region "签名过程"

            JTTWechatWXPayUnifiedOrder TempJTTWechatWXPayUnifiedOrder = _Request;

            Dictionary<String, String> MyDict = new Dictionary<String, String>();
            MyDict.Add("appid", TempJTTWechatWXPayUnifiedOrder.APPID);
            MyDict.Add("mch_id", TempJTTWechatWXPayUnifiedOrder.MerchantID);
            MyDict.Add("device_info", TempJTTWechatWXPayUnifiedOrder.DeviceInfo);
            MyDict.Add("nonce_str", TempJTTWechatWXPayUnifiedOrder.NonceString);
            MyDict.Add("body", TempJTTWechatWXPayUnifiedOrder.Body);
            MyDict.Add("detail", TempJTTWechatWXPayUnifiedOrder.Detail);
            MyDict.Add("attach", TempJTTWechatWXPayUnifiedOrder.Attach);
            MyDict.Add("out_trade_no", TempJTTWechatWXPayUnifiedOrder.OutTradeID);
            MyDict.Add("fee_type", TempJTTWechatWXPayUnifiedOrder.FeeType);
            MyDict.Add("total_fee", TempJTTWechatWXPayUnifiedOrder.TotalFee.ToString());
            MyDict.Add("spbill_create_ip", TempJTTWechatWXPayUnifiedOrder.SpbillCreateIP);
            MyDict.Add("time_start", TempJTTWechatWXPayUnifiedOrder.TimeStart);
            MyDict.Add("time_expire", TempJTTWechatWXPayUnifiedOrder.TimeExpire);
            MyDict.Add("goods_tag", TempJTTWechatWXPayUnifiedOrder.GoodsTag);
            MyDict.Add("notify_url", TempJTTWechatWXPayUnifiedOrder.NotifyURL);
            MyDict.Add("trade_type", TempJTTWechatWXPayUnifiedOrder.TradeType);
            MyDict.Add("product_id", TempJTTWechatWXPayUnifiedOrder.ProductID);
            MyDict.Add("openid", TempJTTWechatWXPayUnifiedOrder.OpenID);

            Dictionary<String, String> NewDict = MyDict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            String CombineString = "";
            foreach (KeyValuePair<String, string> PerPair in NewDict)
            {
                if (!((PerPair.Value == null) || (PerPair.Value == "")))
                {
                    CombineString = CombineString + PerPair.Key + "=" + PerPair.Value + "&";
                }
            }
            CombineString = CombineString + "key=" + _WechatPayAPI;// HttpRuntime.Cache.Get("WechatPayAPI").ToString();
            TempJTTWechatWXPayUnifiedOrder.Sign = CombineString.ToMD5String().ToUpper();

            #endregion

            JTTWechatWXPayUnifiedOrderReturn MyReturn = new JTTWechatWXPayUnifiedOrderReturn();
            String PostData = TempJTTWechatWXPayUnifiedOrder.ObjectToXml<JTTWechatWXPayUnifiedOrder>();
            String PostURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String ReturnData = "";
            try
            {
                ReturnData = NETHelper.TextMessagePost(PostURL, PostData);
                try
                {
                    MyReturn = ReturnData.XmlToObject<JTTWechatWXPayUnifiedOrderReturn>();
                }
                catch (Exception)
                {
                    MyReturn.ReturnCode = "FAIL";
                    MyReturn.ReturnMessage = "序列化失败";
                }
            }
            catch (Exception)
            {
                MyReturn.ReturnCode = "FAIL";
                MyReturn.ReturnMessage = "通讯失败";
            }
            return MyReturn;
        }

        /// <summary>
        /// 微信支付签名
        /// </summary>
        /// <param name="_SignInfo"></param>
        /// <returns></returns>
        public JTTWechatWXPaySignReturn WXPaySign(JTTWechatWXPaySignInfo _SignInfo)
        {
            JTTWechatWXPaySignReturn MyReturn = new JTTWechatWXPaySignReturn();

            Dictionary<String, String> MyDict = new Dictionary<String, String>();
            MyDict.Add("appId", _SignInfo.AppID);
            MyDict.Add("timeStamp", _SignInfo.TimeStamp);
            MyDict.Add("nonceStr", _SignInfo.NonceString);
            MyDict.Add("package", _SignInfo.Package);
            MyDict.Add("signType", "MD5");

            Dictionary<String, String> NewDict = MyDict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            String CombineString = "";
            foreach (KeyValuePair<String, string> PerPair in NewDict)
            {
                if (!((PerPair.Value == null) || (PerPair.Value == "")))
                {
                    CombineString = CombineString + PerPair.Key + "=" + PerPair.Value + "&";
                }
            }
            CombineString = CombineString + "key=" + _SignInfo.WechatPayAPI;// HttpRuntime.Cache.Get("WechatPayAPI").ToString();
            MyReturn.PaySign = CombineString.ToMD5String().ToUpper();
            return MyReturn;
        }

        /// <summary>
        /// 异步通知的验证
        /// </summary>
        /// <param name="_NotifyInfo"></param>
        /// <returns></returns>
        public JTTWechatWXPayNotifyReturn NotifyVerify(JTTWechatWXPayNotifyInfo _NotifyInfo, String _WechatPayAPI)
        {
            JTTWechatWXPayNotifyReturn MyReturn = new JTTWechatWXPayNotifyReturn();

            Dictionary<String, String> MyDict = new Dictionary<String, String>();
            MyDict.Add("return_code", _NotifyInfo.ReturnCode);
            MyDict.Add("return_msg", _NotifyInfo.ReturnMessage);
            MyDict.Add("appid", _NotifyInfo.AppID);
            MyDict.Add("mch_id", _NotifyInfo.MerchantID);
            MyDict.Add("device_info", _NotifyInfo.DeviceInfo);
            MyDict.Add("nonce_str", _NotifyInfo.NonceString);
            MyDict.Add("result_code", _NotifyInfo.RetultCode);
            MyDict.Add("err_code", _NotifyInfo.ErrorCode);
            MyDict.Add("err_code_des", _NotifyInfo.ErrorCodeDescription);
            MyDict.Add("openid", _NotifyInfo.OpenID);
            MyDict.Add("is_subscribe", _NotifyInfo.IsSubscribe);
            MyDict.Add("trade_type", _NotifyInfo.TradeType);
            MyDict.Add("bank_type", _NotifyInfo.BankType);
            MyDict.Add("total_fee", _NotifyInfo.TotalFee.ToString());
            MyDict.Add("coupon_fee", _NotifyInfo.CouponFee == null ? "" : _NotifyInfo.CouponFee.ToString());
            MyDict.Add("fee_type", _NotifyInfo.FeeType);
            MyDict.Add("transaction_id", _NotifyInfo.TransactionID);
            MyDict.Add("out_trade_no", _NotifyInfo.OutTradeID);
            MyDict.Add("attach", _NotifyInfo.Attach);
            MyDict.Add("time_end", _NotifyInfo.TimeEnd);
            MyDict.Add("cash_fee", _NotifyInfo.CashFee);

            Dictionary<String, String> NewDict = MyDict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            String CombineString = "";
            foreach (KeyValuePair<String, string> PerPair in NewDict)
            {
                if (!((PerPair.Value == null) || (PerPair.Value == "")))
                {
                    CombineString = CombineString + PerPair.Key + "=" + PerPair.Value + "&";
                }
            }
            CombineString = CombineString + "key=" + _WechatPayAPI;// HttpRuntime.Cache.Get("WechatPayAPI").ToString();
            if (_NotifyInfo.Sign == CombineString.ToMD5String().ToUpper())
            {
                MyReturn.ReturnCode = "SUCCESS";
                MyReturn.ReturnMessage = "OK";
            }
            else
            {
                MyReturn.ReturnCode = "FAIL";
                MyReturn.ReturnMessage = "校验失败";
            }
            return MyReturn;
        }

        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="_QueryInfo"></param>
        /// <returns></returns>
        public JTTWechatWXPayOrderQueryReturn OrderQuery(JTTWechatWXPayOrderQueryInfo _QueryInfo, String _WechatPayAPI)
        {
            JTTWechatWXPayOrderQueryInfo TempJTTWechatWXPayOrderQueryInfo = _QueryInfo;

            #region "签名过程"

            Dictionary<String, String> MyDict = new Dictionary<String, String>();
            MyDict.Add("appid", TempJTTWechatWXPayOrderQueryInfo.APPID);
            MyDict.Add("mch_id", TempJTTWechatWXPayOrderQueryInfo.MerchantID);
            MyDict.Add("transaction_id", TempJTTWechatWXPayOrderQueryInfo.TransactionID);
            MyDict.Add("out_trade_no", TempJTTWechatWXPayOrderQueryInfo.OutTradeID);
            MyDict.Add("nonce_str", TempJTTWechatWXPayOrderQueryInfo.NonceString);

            Dictionary<String, String> NewDict = MyDict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            String CombineString = "";
            foreach (KeyValuePair<String, string> PerPair in NewDict)
            {
                if (!((PerPair.Value == null) || (PerPair.Value == "")))
                {
                    CombineString = CombineString + PerPair.Key + "=" + PerPair.Value + "&";
                }
            }
            CombineString = CombineString + "key=" + _WechatPayAPI;// HttpRuntime.Cache.Get("WechatPayAPI").ToString();
            TempJTTWechatWXPayOrderQueryInfo.Sign = CombineString.ToMD5String().ToUpper();

            #endregion

            JTTWechatWXPayOrderQueryReturn MyReturn = new JTTWechatWXPayOrderQueryReturn();
            String PostData = TempJTTWechatWXPayOrderQueryInfo.ObjectToXml<JTTWechatWXPayOrderQueryInfo>();
            String PostURL = "https://api.mch.weixin.qq.com/pay/orderquery";
            String ReturnData = "";
            try
            {
                ReturnData = NETHelper.TextMessagePost(PostURL, PostData);
                try
                {
                    MyReturn = ReturnData.XmlToObject<JTTWechatWXPayOrderQueryReturn>();
                }
                catch (Exception e)
                {
                    MyReturn.ReturnCode = "FAIL";
                    MyReturn.ReturnMessage = "序列化失败" + e.Message;
                }
            }
            catch (Exception)
            {
                MyReturn.ReturnCode = "FAIL";
                MyReturn.ReturnMessage = "通讯失败";
            }
            return MyReturn;
        }

        #endregion

        #region "共享收货地址"

        /// <summary>
        /// 地址签名
        /// </summary>
        /// <param name="_Info"></param>
        /// <returns></returns>
        public JTTWechatAddressSignReturn AddressSign(JTTWechatAddressSignInfo _Info)
        {
            JTTWechatAddressSignReturn MyReturn = new JTTWechatAddressSignReturn();
            MyReturn.Sign = "";

            Dictionary<String, String> MyDict = new Dictionary<String, String>();
            MyDict.Add("appid", _Info.AppID);
            MyDict.Add("url", _Info.URL);
            MyDict.Add("timestamp", _Info.TimeStamp);
            MyDict.Add("noncestr", _Info.NonceString);
            MyDict.Add("accesstoken", _Info.AccessToken);

            Dictionary<String, String> NewDict = MyDict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            String CombineString = "";
            foreach (KeyValuePair<String, string> PerPair in NewDict)
            {
                if (!((PerPair.Value == null) || (PerPair.Value == "")))
                {
                    CombineString = CombineString + PerPair.Key + "=" + PerPair.Value + "&";
                }
            }
            CombineString = CombineString.Substring(0, CombineString.Length - 1);

            SHA1 MyMySHA1;
            ASCIIEncoding MyEncoding;
            String ReturnHash = "";
            try
            {
                MyMySHA1 = new SHA1CryptoServiceProvider();
                MyEncoding = new ASCIIEncoding();
                byte[] dataToHash = MyEncoding.GetBytes(CombineString);
                byte[] dataHashed = MyMySHA1.ComputeHash(dataToHash);
                ReturnHash = BitConverter.ToString(dataHashed).Replace("-", "");
                ReturnHash = ReturnHash.ToLower();
            }
            catch (Exception)
            {
                ReturnHash = "";
            }
            MyReturn.Sign = ReturnHash;

            return MyReturn;
        }

        #endregion

        #region "素材"

        /// <summary>
        /// 上传图片，获取图片地址
        /// </summary>
        /// <param name="_ImageUrl"></param>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public String UploadTempImage(String _ImageUrl, String _AccessToken)
        {
            String TempReturn = "";
            WebClient MyWebClient = new WebClient();
            String TempFileName = System.AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid().ToString("D").Replace(" - ", "").ToUpper() + ".jpg";
            try
            {
                MyWebClient.DownloadFile(_ImageUrl, TempFileName);
                byte[] ByteData = MyWebClient.UploadFile(String.Format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", _AccessToken, "image"), TempFileName);//调用接口上传文件
                File.Delete(TempFileName);
                String ReturnString = Encoding.Default.GetString(ByteData);//获取返回值
                JTTWechatMediaUploadReturn TempReturnMedia = ReturnString.JsonToObject<JTTWechatMediaUploadReturn>();
                return TempReturnMedia.MediaID;
            }
            catch (Exception)
            {
                TempReturn = "";
            }
            return TempReturn;
        }

        /// <summary>
        /// 上传图片，获取图片地址,然后要删除这个文件
        /// </summary>
        /// <param name="_ImageFileName"></param>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public String UploadTempImage2(String _ImageFileName, String _AccessToken)
        {
            String TempReturn = "";
            WebClient MyWebClient = new WebClient();
            try
            {
                byte[] ByteData = MyWebClient.UploadFile(String.Format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", _AccessToken, "image"), _ImageFileName);//调用接口上传文件
                File.Delete(_ImageFileName);
                String ReturnString = Encoding.Default.GetString(ByteData);//获取返回值
                JTTWechatMediaUploadReturn TempReturnMedia = ReturnString.JsonToObject<JTTWechatMediaUploadReturn>();
                return TempReturnMedia.MediaID;
            }
            catch (Exception)
            {
                TempReturn = "";
            }
            return TempReturn;
        }

        /// <summary>
        /// 上传图片，获取图片地址,然后不要删除这个文件
        /// </summary>
        /// <param name="_ImageFileName"></param>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public String UploadTempImage3(String _ImageFileName, String _AccessToken)
        {
            String TempReturn = "";
            WebClient MyWebClient = new WebClient();
            try
            {
                byte[] ByteData = MyWebClient.UploadFile(String.Format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", _AccessToken, "image"), _ImageFileName);//调用接口上传文件
                String ReturnString = Encoding.Default.GetString(ByteData);//获取返回值
                JTTWechatMediaUploadReturn TempReturnMedia = ReturnString.JsonToObject<JTTWechatMediaUploadReturn>();
                MyWebClient.Dispose();
                return TempReturnMedia.MediaID;
            }
            catch (Exception)
            {
                TempReturn = "";
            }
            return TempReturn;
        }

        #endregion

        #region 多客服

        /// <summary>
        /// 获取多客服列表
        /// </summary>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public JTTWechatGetKFListReturn GetKFList(String _AccessToken)
        {
            String GetURL = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + _AccessToken;
            String TempJSON = NETHelper.URLGet(GetURL);
            try
            {
                JTTWechatGetKFListReturn MyJTTWechatGetKFListReturn = TempJSON.JsonToObject<JTTWechatGetKFListReturn>();
                return MyJTTWechatGetKFListReturn;
            }
            catch (Exception)
            {
                return new JTTWechatGetKFListReturn();
            }
        }

        /// <summary>
        /// 根据客服账号获取客服昵称
        /// </summary>
        /// <param name="_KFAccount"></param>
        /// <returns></returns>
        public String GetKFNickNameByAccount(String _KFAccount, String _AccessToken)
        {
            String GetURL = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + _AccessToken;
            String TempJSON = NETHelper.URLGet(GetURL);
            try
            {
                JTTWechatGetKFListReturn MyJTTWechatGetKFListReturn = TempJSON.JsonToObject<JTTWechatGetKFListReturn>();
                foreach (var e in MyJTTWechatGetKFListReturn.KFList)
                {
                    if (e.KFAccount == _KFAccount)
                    {
                        return e.KFNickName;
                    }
                }
                return "";
            }
            catch (Exception)
            {
                return "";
            }

        }

        /// <summary>
        /// 获得客服会话信息
        /// </summary>
        /// <param name="_OpenID"></param>
        /// <param name="_AccessToken"></param>
        /// <returns></returns>
        public JTTWechatKFSessionInfo GetKFSessionInfo(String _OpenID, String _AccessToken)
        {
            String GetURL = "https://api.weixin.qq.com/customservice/kfsession/getsession?access_token=" + _AccessToken + "&openid=" + _OpenID;
            String TempJSON = NETHelper.URLGet(GetURL);
            try
            {
                JTTWechatKFSessionInfo MyJTTWechatKFSessionInfo = TempJSON.JsonToObject<JTTWechatKFSessionInfo>();
                return MyJTTWechatKFSessionInfo;
            }
            catch (Exception)
            {
                return new JTTWechatKFSessionInfo();
            }
        }

        #endregion
    }
}
